package com.hc.controller;

import com.hc.entity.User;
import com.hc.mapper.UserMapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;


    @GetMapping("/addUser")
    public String addUser() {
        User user1 = new User(1L, "张三", 2000d);
        User user2 = new User(2L, "李四", 2000d);
        userMapper.insert(user1);
        userMapper.insert(user2);
        return "user";
    }

    @GetMapping("/transfer")
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public String transfer(Long fromId, Long toId, double money) {
        User fromUser = userMapper.findById(fromId);
        User toUser = userMapper.findById(toId);
        fromUser.setMoney(fromUser.getMoney() - money);
        toUser.setMoney(toUser.getMoney() + money);
        userMapper.updateUser(fromUser);
        int i = 1 / 0;
        userMapper.updateUser(toUser);
        return "success";
    }
}
